﻿using System.Threading.Tasks;
using Abp.UI;
using Abp.Domain.Repositories;
using Omu.ValueInjecter;
using App.MultiTenancy.Dto;
using App.BaseObject;
using Abp.Domain.Uow;

namespace App.MultiTenancy
{
    public partial class TenantAppService : ITenantAppService
    {
        private readonly IRepository<Tenant> _tenantRepository;
        public TenantAppService(IRepository<Tenant> tenantRepository)
        {
            _tenantRepository = tenantRepository;
        }
        
		public async Task SaveTenants(BulkDto<TenantDto> dto)
        {
            //批量插入
            foreach (var row in dto.InsertedRows)
            {
                if (await _tenantRepository.CountAsync(b => b.TenancyName == row.TenancyName) > 0)
                {
                    throw new UserFriendlyException(string.Format("名为【{0}】的租户已经存在！", row.TenancyName));
                }
                else
                {
                    var entity = new Tenant();
                    entity.InjectFrom(row);
                    await _tenantRepository.InsertAsync(entity);
                }
            }
            //批量更新
            foreach (var row in dto.UpdatedRows)
            {
                var entity = await _tenantRepository.SingleAsync(s => s.Id == row.Id);
                entity.InjectFrom(row);
            }

            //删除
            //删除
            foreach (var row in dto.DeletedRows)
            {
                if (row.Id.HasValue)
                    await _tenantRepository.DeleteAsync(row.Id.Value);
            }
        }
		
		public async Task<Tenant> GetTenantAsync(int id)
        {
            return await _tenantRepository.FirstOrDefaultAsync(s => s.Id == id);
        }
    }
}
